package com.itheima02;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import jdk.nashorn.internal.ir.CallNode;
import org.junit.Test;

import java.util.HashMap;

public class ObjectMapperTest {
    private ObjectMapper mapper=new ObjectMapper();
    @Test
    public void test01() throws Exception{
        //user转json
        User user = new User("张三", 23);
        String json = mapper.writeValueAsString(user);
        System.out.println("json字符串"+json);
        //json转User
        User user1 = mapper.readValue(json, User.class);
        System.out.println("java对象"+user1);

    }

    @Test
    public void test03() throws Exception {
        //map<String,User>转json
        HashMap<String, User> map = new HashMap<>();
        map.put("黑马一班",new User("张三",23));
        map.put("黑马二班",new User("李四",24));
        String json = mapper.writeValueAsString(map);
        System.out.println("json字符串:"+json);
        //json转map<String,User>
        HashMap<String,User> map2 =mapper.readValue(json,new TypeReference<HashMap<String,User>>(){});
        System.out.println("java对象:"+map2);
    }
}
